package net.wangds.yunz.auth.ctrl;

import net.wangds.yunz.auth.service.AuthService;
import net.wangds.yunz.auth.viewmodel.form.RegUserForm;
import net.wangds.jpa.Sorts;
import net.wangds.jpa.convertor.Page2MultipleRespConv;
import net.wangds.jpa.convertor.PagingForm2PageRequestConv;
import net.wangds.log.helper.LogHelper;
import net.wangds.program.auth.module.AuthAccount;
import net.wangds.utils.JsonUtils;
import net.wangds.validatecode.model.VerifyInfo;
import net.wangds.web.entrypoint.BaseMultipleResp;
import net.wangds.web.entrypoint.BaseResp;
import net.wangds.web.entrypoint.PagingForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/auth")
public class ArtWorkAuthCtrl {

    @Autowired
    private AuthService mmServM10Auth;

    @RequestMapping(value="/reg", method = RequestMethod.POST)
    public BaseResp<Object> reg(
            @RequestBody(required = false) RegUserForm form
    ){
        LogHelper.dev(()->"注册："+ JsonUtils.toJsonStr(form));

        if(!mmServM10Auth.validateVerifyCode(form.getVerifyToken(), form.getVerifyCode())){
            return BaseResp.of(null)
                    .msg("验证码错误,可尝试点击验证码图片刷新验证码，并用新的验证码重新提交")
                    .code(-2);
        }


        if(StringUtils.isEmpty(form.getLoginname())){
            return BaseResp.of(null).msg("登录名为空").code(-6);
        }

        if(StringUtils.length(form.getLoginname())<6){
            return BaseResp.of(null).msg("登录名长度小于6位").code(-5);
        }

        if(StringUtils.isEmpty(form.getPassword())){
            return BaseResp.of(null).msg("密码为空").code(-4);
        }

        if(!StringUtils.equals(form.getPassword(), form.getPasswordAgain())){
            return BaseResp.of(null).msg("两次输入的密码不同").code(-3);
        }

      boolean exists = mmServM10Auth.existsByLoginname(form.getLoginname());
        if(exists){
            return BaseResp.of(null).msg("用户登录名已存在").code(-1);
        }
        AuthAccount acc = mmServM10Auth.regNewAccount(form.getLoginname(), form.getPassword(), "",
                form.getUsername(), form.getNickname(), "", "", "");

        List<GrantedAuthority> auth = new ArrayList<>();

        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(acc.getId(), acc, auth));

        return BaseResp.of(SecurityContextHolder.getContext().getAuthentication());
    }

    @RequestMapping(value="/me", method = RequestMethod.POST)
    public BaseResp<UserDetails> me(
            @RequestHeader(HttpHeaders.AUTHORIZATION)
            String token
    ){
        //LogHelper.dev("/me:token="+token);
        return BaseResp.of(mmServM10Auth.getUserDetail(StringUtils.replaceOnce(token, "Bearer ","")));
    }


    @RequestMapping(value="/verifycode", method = RequestMethod.GET)
    public BaseResp<VerifyInfo> updateVerifyCode(){
        return BaseResp.of(mmServM10Auth.fetchVerifyCode());
    }



    @RequestMapping(value="/famous", method = RequestMethod.POST)
    public BaseMultipleResp<AuthAccount> famous(
            @RequestBody PagingForm form){
        return Objects.requireNonNull(new Page2MultipleRespConv<AuthAccount>().convert(
                mmServM10Auth.findFamous(
                        StringUtils.trim(form.getKeywords()),
                        new PagingForm2PageRequestConv(() -> Sorts.createTm_desc).convert(form)))).keywords(form.getKeywords());
    }


    @RequestMapping(value="/byId/{id}", method = RequestMethod.GET)
    public BaseResp<AuthAccount> byId(
            @PathVariable("id") String id
    ){
        return BaseResp.of( mmServM10Auth.findById(id).orElse(null));
    }


}
